package com.bloveoacom.weichi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.blankj.utilcode.util.ToastUtils;
import com.bloveoacom.base.BaseActivity;
import com.bloveoacom.base.UserInfoBean;
import com.bloveoacom.exception.ApiException;
import com.bloveoacom.http.HttpMethods;
import com.bloveoacom.http.HttpResult;
import com.bloveoacom.http.MessageModel;
import com.bloveoacom.http.RxBus;
import com.bloveoacom.http.RxHelper;
import com.bloveoacom.observer.BaseSubscriber2;
import com.bloveoacom.util.AESCipher;
import com.bloveoacom.util.DialogUtil;
import com.bloveoacom.util.GsonUtil;
import com.bloveoacom.util.NumberUtil;
import com.bloveoacom.util.StringUtils;
import com.bloveoacom.util.ToastUtil;
import com.bloveoacom.weichi.R;
import com.bloveoacom.weichi.bean.CreateEosWalletBean;
import com.bloveoacom.weichi.bean.RewardBean;
import com.bloveoacom.weichi.bean.SimpleBean;
import com.bloveoacom.weight.InputDialog;
import com.bloveoacom.weight.LlkjToolBar;
import com.bloveoacom.weight.RichTextEditor;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.reactivestreams.Publisher;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static com.bloveoacom.util.AESCipher.KEY;

/**
 * author: zhu.px
 * e-mail: 1271901673@qq.com
 * time  : 2018/6/26
 * desc  : 发布帖子
 */
public class ReleasePostActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    LlkjToolBar titleBar;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.et_new_content)
    RichTextEditor etNewContent;
    @BindView(R.id.tv_bar)
    EditText tvBar;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_release_post;
    }

    @Override
    public void initView() {
        titleBar.setToolBar("发布",
                true, "", R.drawable.ic_back, true, "", LlkjToolBar.isNull);

    }

    @Override
    protected View getViewSetTB() {
       return titleBar;
    }



    @Override
    public void initData() {

    }

    @Override
    public void getBundleExtras(Bundle extras) {
    }

    @Override
    public void initListener() {

    }
    @OnClick({R.id.tv_photo, R.id.tv_release})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_photo:
                openGallery();
                break;
            case R.id.tv_release:
                release();
                break;
            default:
                break;
        }
    }

    private void openGallery() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .theme(R.style.photo_style)
                .maxSelectNum(9)
                .minSelectNum(0)
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(true)
                .previewEggs(true)
                .compress(true)
                .synOrAsy(false)
                .minimumCompressSize(500)
                .glideOverride(160, 160)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private String title,cellnum;
    private void release() {
         title = etTitle.getText().toString().trim();
         cellnum = tvBar.getText().toString().trim();
        if (StringUtils.isEmpty(title)) {
            ToastUtils.showShort("请输入标题");
            return;
        }
        String content = getEditData();
        if (StringUtils.isEmpty(content)) {
            ToastUtils.showShort("请输入内容");
            return;
        }
         if(NumberUtil.getIntByStr(cellnum)==0){
             ToastUtils.showShort("请输入楼层数");
             return;
         }
        showInputPasswordDialog();
    }

    /**
     * 负责处理编辑数据提交等事宜，请自行实现
     */
    private String getEditData() {
        List<RichTextEditor.EditData> editList = etNewContent.buildEditData();
        StringBuilder content = new StringBuilder();
        for (RichTextEditor.EditData itemData : editList) {
            if (itemData.inputStr != null) {
                content.append(itemData.inputStr);
            } else if (itemData.imagePath != null) {
                content.append("<img src=\"").append(itemData.imagePath).append("\"/>");
            }
        }
        return StringUtils.replaceNTB(content.toString());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> localMedias = PictureSelector.obtainMultipleResult(data);
                    Observable.fromIterable(localMedias)
                            .filter(localMedia -> localMedia != null)
                            .map(localMedia -> StringUtils.isEmpty(localMedia.getCompressPath()) ?
                                    localMedia.getPath() : localMedia.getCompressPath())
                            .subscribe(s -> etNewContent.insertImage(s, etNewContent.getMeasuredWidth()));
                    break;
                default:
                    break;
            }
        }
    }
    private InputDialog  inputPasswordDialog;

    private String sign;
    private void showInputPasswordDialog() {
        if (inputPasswordDialog == null) {
            inputPasswordDialog = new InputDialog(this, "输入密码", "Password", true, false, R.style.MyDialogStyle);
            inputPasswordDialog.setItemClickListener(new InputDialog.ItemClickListener() {
                @Override
                public void left() {

                }

                @Override
                public void right(String content) {
                    DialogUtil.dissDialog(inputPasswordDialog);
                    HttpMethods.getInstance().getHttpService().findTimeStamp(UserInfoBean.getInstance()
                            .getToken()).subscribeOn(Schedulers.io()).
                            flatMap((Function<HttpResult<Object>, Flowable<RichTextEditor.EditData>>) objectHttpResult -> {
                                if (objectHttpResult.isOk()) {
                                    Object o = objectHttpResult.data;
                                    SimpleBean simpleBean = GsonUtil.GsonToBean(GsonUtil.GsonString(o), SimpleBean.class);
                                    String s = AESCipher.decryptAES(simpleBean.timeStamp);
                                    CreateEosWalletBean transInfoBean = new CreateEosWalletBean(content, s);
                                    sign = AESCipher.encryptAES(GsonUtil.GsonString(transInfoBean), KEY);
                                    return Flowable.fromIterable(etNewContent.buildEditData());
                                } else {
                                    return Flowable.error(new ApiException(objectHttpResult.code, objectHttpResult.msg));
                                }
                            }).filter(editData -> editData.imagePath != null).map(editData -> editData.imagePath).toList().flatMapPublisher((Function<List<String>, Publisher<HttpResult<List<String>>>>) strings -> {
                                if (strings != null && strings.size() > 0) {
                                    final LinkedHashMap<String, RequestBody> map = new LinkedHashMap<>();
                                    for (int i = 0; i < strings.size(); i++) {
                                        File file = new File(strings.get(i));
                                        if (file.exists()) {
                                            map.put("file\";filename=\"" + file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
                                        }
                                    }
                                    return HttpMethods.getInstance().getHttpService().uploadImgs(map);
                                } else {
                                    HttpResult<List<String>> httpResult = new HttpResult<>();
                                    httpResult.code = HttpMethods.HTTP_SUCCESS;
                                    httpResult.data = new ArrayList<>();
                                    return Flowable.just(httpResult);
                                }
                            }).map(listHttpResult -> listHttpResult.data).flatMap((Function<List<String>, Publisher<HttpResult<RewardBean>>>) s -> {
                        StringBuilder sb = new StringBuilder();
                        List<String> contents = StringUtils.cutStringByImgTag(getEditData());
                        if (s != null && s.size() > 0) {
                            int photoIndex = 0;
                            for (int i = 0; i < contents.size(); i++) {
                                String text = contents.get(i);
                                if (text.contains("<img")) {
                                    sb.append("<img src=\"").append(s.get(photoIndex)).append("\"/>");
                                    photoIndex++;
                                } else {
                                    sb.append(text);
                                }
                            }
                        } else {
                            for (int i = 0; i < contents.size(); i++) {
                                sb.append(contents.get(i));
                            }
                        }
                        return HttpMethods.getInstance().getHttpService().releasePost(cellnum, etTitle.getText().toString().trim(), sb.toString(),
                                UserInfoBean.getInstance().getToken(), sign);
                    }).compose(RxHelper.io_main()).subscribeWith(new BaseSubscriber2<HttpResult<RewardBean>>(ReleasePostActivity.this) {
                        @Override
                        public void onNext(HttpResult<RewardBean> o) {
                            RxBus.getInstance().send(new MessageModel(MessageModel.TU_TYPE_REFRESH_POST, ""));
                            RxBus.getInstance().send(new MessageModel(MessageModel.TU_TYPE_UPDATEUSERINFO, ""));
                            ToastUtil.makeShortText(mContext, getString(R.string.release_success));
                            finish();
                        }
                    });

                }
            });
        }
        inputPasswordDialog.show();
    }

}
